/**
 * Created by xzr on 2019/3/7.
 */
var isAutoLogin = document.getElementById('isAutoLogin');
document.write("<script language='javascript' src='http://react.file.alimmdn.com/aes.js'></script>");
document.write("<script language='javascript' src='./public/javascripts/common/md5.js'></script>");
//submit 表单提交
function checkUser() {
    var userPhone = $("#userTel").val();
    var userPwd = $("#userPwd").val();

    if(userPhone=="" || userPhone==null) {
        popupTip('手机号码不能为空');
        return;
    }
    if(userPwd=="" || userPwd==null) {
        popupTip('密码不能为空');
        return;
    }

    loginByPhone(userPhone,userPwd);
}

//是否自动登录
function AutoLogin() {
    if(isAutoLogin.checked) {
        layer.open({
            content: '选择自动登录后可能存在安全隐患，请您考虑清楚后再做决定！'
            ,btn: ['知道了']
        });
    }
}

$(function () {
    // 清空数据
    $('.clearIcon_name').click(function () {
        $('#userTel').val("");
    })
    $('.clearIcon_alipay').click(function () {
        $('#userPwd').val("");
    })
})

// 登录
function loginByPhone(userPhone,userPwd) {
    var user = {
        account: userPhone,
        password: userPwd,
        time: new Date().getTime()
    }

    user.password = encryption(user.password);

    var param = getSortObjByAsciiWithObj(user, 'zxw201905142059');
    console.log(param);
    $.ajax({
        type: 'post',
        dataType: 'json',
        url: "http://127.0.0.1:3001/users/",
        data: param,
        success: function(rsp) {
            console.log(rsp);
            if(rsp.status == 200) {
                window.location.href='./center.html?account=' + rsp.account;
            }
            else {
                popupTip(rsp.err);
            }
        },
        error: function () {
            popupTip('登陆失败');
        }
    });
}

/**
 * AES加密
 * return utf8
 */
function encryption(word) {
    const key = CryptoJS.enc.Utf8.parse("1234123412ABCDEF");  //十六位十六进制数作为密钥
    const iv = CryptoJS.enc.Utf8.parse('ABCDEF1234123412');   //十六位十六进制数作为密钥偏移量
    
    let srcs = CryptoJS.enc.Utf8.parse(word);
        let encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
        return encrypted.ciphertext.toString().toUpperCase();
}

//返回拼接上sign的请求对象
function getSortObjByAsciiWithObj(obj, secret) {

    var sortArrStr = getSortStrByAsciiWithObj(obj); //组成按字母顺序排序的字符串str
    var waitSecretStr = secret + sortArrStr + secret; //str前后拼接secret的方式组成待加密字符串 
    var stringSign = hex_md5(waitSecretStr);//对加密字符串进行md5形成签名
    var sign = stringSign.toLocaleLowerCase(); //将签名sign转化为纯小写
    obj.sign = sign;
    return obj;
}

//构造按Ascii码顺序组成的字符串
function getSortStrByAsciiWithObj(obj) {
    var arr = [];
    for (var key in obj) {
        arr.push(key);
    }
    var sortArr = getsParaFromArr(arr); //返回按字母顺序排序的数组
    var sortArrStr = '';
    sortArr.forEach(function (key) {
        var item = {};
        item[key] = obj[key];
        sortArrStr += key + '=' + obj[key];
    });

    // console.log('sortArrStr = ' + sortArrStr);
    return sortArrStr; //str="key=JF201811212112125phone=18605996973score=11time=1545449321396"
}

//传入数组，返回按Ascii码排序的数组
function getsParaFromArr(sParaTemp) {
    var sPara = [];
    //除去数组中的空值和签名参数
    for (var i1 = 0; i1 < sParaTemp.length; i1++) {
        var value = sParaTemp[i1];
        if (value == null || value == "" || value == "sign") {
            continue;
        }
        sPara.push(value);
    }
    sPara = sPara.sort();
    return sPara;
}

